<template>
  <div class="container">
    <Header :headerHeight="headerHeights" title="数据上传" @doBack="doBack" rightText="上传" @doRightClick="uploadFansData"
      class="header"></Header>
    <div class="content" :style="{ height: contentHeight }">
      <div class="fans-num">
        <van-field v-model="digit" type="digit" label="粉丝数" placeholder="请输入粉丝数" @input="uploadfans" />
        <i class="icon"></i>
      </div>
      <div class="upload-screenshot">
        <van-field name="uploader" label="上传粉丝截图">
          <template #input>
            <van-uploader v-model="fileList" :action="uploadUrl" :max-count="1" :before-read="beforeRead" reupload
              accept=".jpeg,.png,.jpg" :after-read="afterRead" />
          </template>
        </van-field>
        <div class="tip">*准确可信的截图是通过的基础</div>
        <i class="icon"></i>
      </div>
      <div class="example">
        <div class="title">粉丝截图示例</div>
        <div class="example-text">
          请上传如图所示截图——个人<span v-if="route.query.channelName == 'xiaohongshu'">小红书</span><span
            v-if="route.query.channelName == 'wechatVideo'">视频号</span>主页，完整展示
          <span style="color: #FF7744;">关注粉丝数量</span>
          ；若填写粉丝数与截图粉丝数不一致，将审核不通过
        </div>
      </div>
      <div class="screenshot" v-if="route.query.channelName == 'xiaohongshu'"
        :style="{ background: `url(${xiaohongshuScreenshot})` }"></div>
      <div class="screenshot" v-if="route.query.channelName == 'wechatVideo'"
        :style="{ background: `url(${wechatVideoScreenshot})` }"></div>
    </div>
  </div>
  <Loading v-if="pageLoading" loadingText="上传中.."></Loading>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { getAccountInfos, headerHeight } from "@/../utils";
import Header from '../components/NewNavbar.vue'
import { collectEvent } from "@/../utils/bridge";
import { Dialog } from "vant";
import { reqUploadImage, reqUploadUrl } from "../api";
import { Toast } from "vant";
import { getUrlParams } from "../utils";
import Loading from "../components/Loading.vue";
import xiaohongshuScreenshot from "../asset/img/xiaohongshu.png";
import wechatVideoScreenshot from "../asset/img/wechatVideo.png";
const router = useRouter();
const route = useRoute();
const pageLoading = ref(false);
console.log("route.query.channel", route.query.channelName);

// 获取状态栏高度
let headerHeights = ref('44px')
if (headerHeight) {
  headerHeights.value = headerHeight()
}
const contentHeight = ref('100vh')
contentHeight.value = `calc(100vh - ${headerHeights.value})`
const doBack = () => {
  history.back();
}

// 定义粉丝量
const digit = ref("");

// 定义预览列表
const fileList = ref([])

// 获取iobs上传路径和token
const uploadUrl = ref("");
const fileKey = ref("");
const token = ref("");
const retryTimes = ref(0);

const getUploadUrl = async (userId) => {
  const { code, data, msg } = await reqUploadUrl(userId);
  if (code == 0 && data.result) {
    uploadUrl.value = data.result.uploadUrl;
    fileKey.value = data.result.fileKey;
    token.value = data.result.token;
    retryTimes.value++;
  }
  if (code != 0) {
    Toast(`获取fileKey异常\ncode${code} ${msg}`);
  }
};

// 上传前后两个钩子
const userFile = ref(null);

const beforeRead = (file) => {
  const typeList = ["image/jpg", "image/jpeg", "image/png"];
  if (typeList.indexOf(file.type) === -1) {
    Toast("请上传正确格的图片");
    return false;
  }
  if (file.size > 5 * 1024 * 1024) {
    Toast("文件大小不能超过5M");
    return false;
  }
  setTimeout(() => {
    traceDataImage(route.query.channelName);
  }, 500);
  return true;
};

const afterRead = (file) => {
  console.log(">>>> file >>>>", file);
  userFile.value = file;
};

// 上传粉丝数和截图
const pointToast = ref('');
const uploadFansData = async () => {
  if (!digit.value || !userFile.value || fileList.value.length === 0) {
    Toast("请上传粉丝数和粉丝截图");
    return;
  }
  if (!fileKey.value) {
    pageLoading.value = true;
    await getUploadUrl(userId.value);
    pageLoading.value = false;
    setTimeout(() => {
      retryTimes.value < 5 ? Toast('网络异常，请重试') : Toast('fileKey获取异常，请稍后再试');
    }, 300)
    return;
  } else {
    pageLoading.value = true;
    const formData = new FormData();
    formData.append("file", userFile.value.file);
    formData.append("token", token.value);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", uploadUrl.value, true);
    xhr.onload = async () => {
      if (xhr.status === 200) {
        console.log("上传成功", xhr.responseText);
        const { code, data, msg } = await reqUploadImage(
          userId.value,
          route.query.channelName,
          digit.value,
          fileKey.value
        );
        pageLoading.value = false;
        if (code == 0 && data) {
          console.log(data);
          pointToast.value = data.result.toast;
          setTimeout(() => {
            Dialog({
              width: 280,
              message: "系统审核中，请耐心等待，审核完成后数据将更新展示。",
              confirmButtonText: "我知道了",
              confirmButtonColor: "#FF7744"
            }).then(() => {
              router.push(`/myData?from=${getUrlParams('from')}`);
              setTimeout(() => {
                if (pointToast.value) {
                  Toast(pointToast.value)
                }
              }, 500);
            });
          }, 300);
        } else {
          Toast(`数据或网络异常\ncode${code} ${msg}`);
        }
      } else {
        console.log("上传失败", xhr.responseText);
      }
    };
    xhr.onerror = function () {
      console.log("请求发生错误");
    };
    xhr.send(formData);
  }
  setTimeout(() => {
    traceDataClick(route.query.channelName);
  }, 500);
};

// 用户输入粉丝数 （埋点）
const uploadfans = (data) => {
  console.log(">>>> 粉丝数： >>>>", data.data);
  setTimeout(() => {
    traceDatafans(route.query.channelName);
  }, 500);
};

// 挂载获取用户id
const userId = ref("");
onMounted(async () => {
  const { agentNo } = await getAccountInfos();
  userId.value = agentNo;
  getUploadUrl(userId.value);
});


const traceDatafans = async (type) => {
  console.log("traceDatafans");
  await window.TrackPoint.pageStart("P02787");
  setTimeout(() => {
    collectEvent({
      eventId: "C12365", // 事件id
      eventTitle: "IP工坊-数据上传-点击填写", // 事件名称
      parameters: {
        empno: userId.value,
        type,
        IP: JSON.parse(window.localStorage.getItem("IP")),
      },
    });
  }, 500);
};
const traceDataImage = async (type) => {
  console.log("traceDataImage");
  await window.TrackPoint.pageStart("P02787");
  setTimeout(() => {
    collectEvent({
      eventId: "C12366", // 事件id
      eventTitle: "IP工坊-数据上传-上传截图", // 事件名称
      parameters: {
        empno: userId.value,
        type,
        IP: JSON.parse(window.localStorage.getItem("IP")),
      },
    });
  }, 500);
};
const traceDataClick = async (type) => {
  console.log("traceDataClick");
  await window.TrackPoint.pageStart("P02787");
  setTimeout(() => {
    collectEvent({
      eventId: "C12367", // 事件id
      eventTitle: "IP工坊-数据上传-点击上传", // 事件名称
      parameters: {
        empno: userId.value,
        type,
        IP: JSON.parse(window.localStorage.getItem("IP")),
      },
    });
  }, 500);
};
</script>

<style lang="less" scoped>
.header {

  :deep(.right-text) {
    color: #FF7744 !important;
    font-size: 17px !important;
    font-weight: 500 !important;
    font-family: PingFangSC-Medium !important;
  }
}

.container {
  width: 100%;
  height: 100%;
  background-color: #f7f7f7;

  .content {
    width: 100%;
    overflow: scroll;
    -webkit-overflow-scroll: touch;
    margin-top: 10px;
    background-color: #f7f7f7;
    background-color: #f7f7f7;

    :deep(.van-field__label) {
      font-family: PingFangSC-Regular;
      font-size: 15px;
      color: #000000;
      letter-spacing: 0;
      font-weight: 400;
    }

    .fans-num {
      position: relative;

      .van-cell {
        height: 54px;
        background: #ffffff;
        box-shadow: inset 0px -0.5px 0px 0px rgba(224, 224, 224, 1);
        display: flex;
        align-items: center;
        padding-right: 36px;

        :deep(.van-field__control) {
          opacity: 0.6;
          font-family: PingFangSC-Regular;
          font-size: 15px;
          color: #000000;
          letter-spacing: 0;
          text-align: right;
          font-weight: 400;
        }
      }

      .icon {
        background: url("../asset/icons/more_grey@2x.png") no-repeat;
        background-size: 100% 100%;
        width: 16px;
        height: 16px;
        position: absolute;
        top: 20px;
        right: 15px;
        z-index: 1;
      }
    }

    .upload-screenshot {
      position: relative;

      .van-cell {
        :deep(.van-field__control) {
          display: inline-block;
          text-align: right;
          padding-right: 12px;
        }
      }

      .icon {
        background: url("../asset/icons/more_grey@2x.png") no-repeat;
        background-size: 100% 100%;
        width: 16px;
        height: 16px;
        position: absolute;
        top: 28px;
        right: 15px;
        z-index: 1;
      }

      .tip {
        position: absolute;
        top: 38px;
        left: 15px;
        z-index: 1;
        font-family: PingFangSC-Regular;
        font-size: 13px;
        color: rgba(0, 0, 0, 0.6);
        letter-spacing: 0;
        font-weight: 400;
      }

      :deep(.van-uploader-size) {
        all: inherit;
      }

      :deep(.van-uploader__input) {
        width: 44px !important;
        height: 44px !important;
      }

      :deep(.van-icon__image) {
        width: 44px;
        height: 44px;
      }
    }
  }

  .example {
    .title {
      font-family: PingFangSC-Regular;
      font-size: 15px;
      color: #000000;
      letter-spacing: 0;
      font-weight: 400;
      margin-top: 17px;
      margin-left: 15px;
    }

    .example-text {
      font-family: PingFangSC-Regular;
      font-size: 13px;
      color: rgba(0, 0, 0, 0.60);
      letter-spacing: 0;
      line-height: 18px;
      font-weight: 400;
      margin: 0 15px;
      margin-top: 7px;
    }
  }

  .screenshot {
    margin: 15px;
    width: 345px;
    height: 647px;
    background-size: cover !important;
    margin-bottom: 100px;
  }

  :deep(.van-uploader__upload-icon) {
    z-index: -1; // 隐藏默认图标
  }

  :deep(.van-uploader__upload) {
    background: url("../asset/icons/screencut_list_default36x36@3x.png") no-repeat;
    background-size: 100% 100%;
  }
}
</style>